package com.itheima.controller;

import com.itheima.bean.User;
import com.itheima.common.R;
import com.itheima.service.UserService;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author hebing
 * @version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送短信
     *
     * @param user
     * @param session
     * @return
     */
    @GetMapping("/smscode")
    public R sendMessage(User user, HttpSession session) {
        //获取手机号
        String phone = user.getPhone();
        //在这里调用工具类生成六位数验证码
        String code = ValidateCodeUtils.generateValidateCode4String(6);
        //判断手机号非空
        if (phone != null && phone.length() > 0) {
            //调用工具类发送短信
            //SMSUtils.sendMessage("瑞吉点餐",code,phone,"");
            //将手机号和验证码保存到session域对象中 只要服务器不关闭 将一直存在该值
            session.setAttribute(phone, code);
            //为了方便前端填写code这里直接返回code
            return R.success(code);
        }
        return R.error("验证码发送失败");
    }

    /**
     * 登录
     *
     * @param map
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Map<String, String> map, HttpSession session) {
        System.out.println("来到了登录界面...");
        //获取前端提交的手机号
        String phone = map.get("phone");
        //获取前端提交的验证码
        String code = map.get("code");
        //判断验证码和session中存储的验证码是否一致
        String valCode = (String) session.getAttribute(phone);
        //一致表示登录成功
        if (code.equalsIgnoreCase(valCode)) {
            //调用service查询数据库
            User user = userService.selectUser(phone);
            //将user对象存放到session域对象中
            session.setAttribute("user",user);
            return R.success("登录成功");
        } else {
            return R.error("登录失败");
        }
    }
}
